
import { useEffect, useState } from 'react'

import {getBannerList,getNavList, getProList} from '../../api/home'

import { View, Swiper, SwiperItem, Image, Text } from '@tarojs/components'

import { AtGrid } from "taro-ui"

import Pro from '../../components/pro'

// 是 Taro 专有的 hooks 
import {useReachBottom, usePullDownRefresh} from '@tarojs/taro'
import Taro from "@tarojs/taro"


const Home = () => {

  const [bannerList,setBannerList] = useState()
  const [proList,setProList] = useState()
  const [count,setCount] = useState(2)
  const [navList] = useState(getNavList())

  useEffect(()=>{
    // 获取轮播图数据
    getBannerList().then(res => {
      // console.log(res);
      setBannerList(res.data)
    })

    getProList().then(res => {
      setProList(res.data)
    })

  }, [])

  // 上拉加载更多
  useReachBottom(()=>{
    getProList({count}).then(res => {
      if(res.data.lengtn <= 0){
        // 没有数据，给出轻提示
      }else {
        setProList([...proList, ...res.data])
        setCount(count + 1)
      }
      
    })
  })

  // 下拉刷新
  usePullDownRefresh(()=>{
    // console.log('下拉了');
    getProList().then(res => {
        setProList(res.data)
        setCount(2)
        Taro.stopPullDownRefresh()
    })
  })

  return (
    <View>
        <Swiper
        className='test-h'
        indicatorColor='#999'
        indicatorActiveColor='#333'
        circular
        indicatorDots
        autoplay
        style={{height: 200}}>
        { bannerList && bannerList.map(item => {
          return (
            <SwiperItem key={item.bannerid}>
              <Image style={{width: '100%'}} src={item.img}></Image>
            </SwiperItem>
          )
        }) }
        
      </Swiper>

      <View style={{margin: '20px 0'}}>
        {navList && <AtGrid columnNum={5} hasBorder={false} data={navList} />}
      </View>

      <View>
        {proList && proList.map(item => {
          return (<Pro 
              key={item.proid}
              title={item.proname}
              img={item.img1}
              originprice={<Text>{item.originprice}</Text>}
            >
              <Text>{item.category}</Text>
            </Pro>)
        })}
      </View>

    </View>
  )
}

export default Home
